<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品计划</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        /* iOS风格简约美学 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f7f7f7;
            color: #333;
        }

        .admin-layout {
            background-color: #f7f7f7;
        }

        .content-wrapper {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            padding: 24px;
            margin: 20px;
        }

        .content-header {
            margin-bottom: 24px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 16px;
        }

        #pageTitle {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        /* iOS风格表单 */
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 8px;
            display: block;
        }

        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }

        .form-control, .form-select {
            height: 44px;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 0 16px;
            font-size: 16px;
            transition: all 0.2s ease;
            width: 100%;
            background-color: #f9f9f9;
        }

        .form-control:focus, .form-select:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
            background-color: #fff;
            outline: none;
        }

        /* 按钮样式 */
        .btn {
            height: 44px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

        .btn-secondary {
            background-color: #f2f2f7;
            border-color: #f2f2f7;
            color: #28a745;
        }

        .btn-secondary:hover {
            background-color: #e5e5ea;
            border-color: #e5e5ea;
        }

        .btn-action {
            min-width: 120px;
        }

        /* 左侧菜单样式 */
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        /* 表格样式 */
        .result-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 20px;
        }

        .result-table th, .result-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .result-table th {
            background-color: #f7f7f7;
            font-weight: 600;
            color: #333;
            position: sticky;
            top: 0;
        }

        .result-table tr:last-child td {
            border-bottom: none;
        }

        .result-table tr:hover {
            background-color: #f9f9f9;
            transition: background-color 0.2s;
        }

        .result-table tr:nth-child(even) {
            background-color: #fcfcfc;
        }

        .result-table th:first-child {
            border-radius: 10px 0 0 0;
        }

        .result-table th:last-child {
            border-radius: 0 10px 0 0;
        }

        .result-table tbody tr:last-child td:first-child {
            border-radius: 0 0 0 10px;
        }

        .result-table tbody tr:last-child td:last-child {
            border-radius: 0 0 10px 0;
        }

        /* 数量控制按钮 */
        .quantity-controls {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .quantity-input {
            width: 60px;
            text-align: center;
            padding: 6px 10px;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
            background-color: #f9f9f9;
        }

        .quantity-btn {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            background-color: #f2f2f7;
            border: 1px solid #e0e0e0;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .quantity-btn:hover {
            background-color: #e5e5ea;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .content-wrapper {
                padding: 16px;
                margin: 10px;
            }

            .form-container {
                padding: 0;
            }

            .result-table {
                display: block;
                width: 100%;
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">员工</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="../homepage/employee_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu active">
                    <li><a href="../product/product_plan_list.html">查看生产计划</a></li>
                    <li><a href="../product/product_plan_commit.html" class="active">提交完成情况</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <div class="form-group">
                <label for="planSelect" class="form-label">选择生产计划</label>
                <select id="planSelect" class="form-select"></select>
                <button id="searchBtn" class="btn btn-primary btn-action">搜索</button>
            </div>
            <div id="resultArea"></div>
            <div id="submissionForm" style="display: none; margin-top: 20px;">
                <div class="form-group">
                    <label for="description" class="form-label">描述</label>
                    <textarea id="description" class="form-control" rows="3" placeholder="请输入描述信息"></textarea>
                </div>
                <button id="submitBtn" class="btn btn-primary btn-action">提交</button>
            </div>
        </div>
    </main>
</div>


<script>
    // 菜单展开/收起功能
    document.addEventListener('DOMContentLoaded', function () {
         var menuItems = document.querySelectorAll('.menu-item > a');
    menuItems.forEach(function (item) {
        item.addEventListener('click', function (e) {
            var parent = item.parentElement;
            // 判断是否为可展开的菜单（包含submenu的项）
            if (parent.querySelector('.submenu')) {
                // 只对可展开的菜单阻止默认行为
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            }
            // 对直接链接（如首页）不阻止默认行为，允许跳转
        });
    });

        // 默认展开产品管理菜单
        const productMenuItem = document.querySelector('.menu-item:nth-child(4)');
        if (productMenuItem) {
            productMenuItem.classList.add('active');
        }

        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href')?.endsWith(filename)) {
                link.classList.add('active');
            }
        });

        // 加载生产计划选项
        loadProductionPlans();

        // 搜索按钮点击事件
        document.getElementById('searchBtn').addEventListener('click', function() {
            const selectedOption = document.getElementById('planSelect').selectedOptions[0];
            if (!selectedOption) {
                alert('请选择一个生产计划');
                return;
            }
            const planId = selectedOption.value;
            searchProductsByPlanId(planId);
        });

        // 提交按钮点击事件
        document.getElementById('submitBtn').addEventListener('click', submitProductionData);
    });

    // 退出登录
    function logout() {
        // 实现退出登录功能
        alert('退出登录');
        window.location.href = '../../login.html';
    }

    // 加载生产计划选项
    function loadProductionPlans() {
        fetch('http://localhost:8080/api/product_plans')
           .then(response => response.json())
           .then(data => {
                const select = document.getElementById('planSelect');
                data.forEach(plan => {
                    const option = document.createElement('option');
                    option.value = plan.plan_id;
                    option.textContent = `${plan.start_time}~${plan.end_time}`;
                    select.appendChild(option);
                });
            })
           .catch(error => console.error('加载生产计划失败:', error));
    }

    // 根据计划 ID 搜索产品
    function searchProductsByPlanId(planId) {
         let userInfo = '未登录';
  try {
    const userData = localStorage.getItem('userInfo');
    if (userData) {
      const user = JSON.parse(userData);
      userInfo = user.name || '未登录';
    }
  } catch (e) { /* 忽略错误 */ }
        fetch(`http://localhost:8080/api/Product_Plan_Details/plan/${planId}`)
           .then(response => response.json())
           .then(details => {
                const productCodes = details.map(detail => detail.product_code);
                const productPromises = productCodes.map(code => {
                    return fetch(`http://localhost:8080/api/products/search?keyword=${code}`)
                       .then(response => response.json())
                       .then(products => products.filter(product => product.operatorName === userInfo));
                });

                Promise.all(productPromises)
                   .then(results => {
                        const combinedResults = results.flat();
                        displayResults(combinedResults, details, planId);
                    })
                   .catch(error => console.error('搜索产品失败:', error));
            })
           .catch(error => console.error('获取计划详情失败:', error));
    }

    // 以表格形式显示搜索结果
    function displayResults(products, details, planId) {
        const resultArea = document.getElementById('resultArea');
        resultArea.innerHTML = '';

        if (products.length === 0) {
            resultArea.innerHTML = '<div class="alert alert-info">没有找到匹配的产品</div>';
            document.getElementById('submissionForm').style.display = 'none';
            return;
        }

        // 保存当前选中的计划ID
        resultArea.dataset.planId = planId;

        const table = document.createElement('table');
        table.classList.add('result-table');
        table.innerHTML = `
            <thead>
                <tr>
                    <th>产品代码</th>
                    <th>产品名称</th>
                    <th>外观尺寸</th>
                    <th>批次</th>
                    <th>加工方法</th>
                    <th>完成数量</th>
                </tr>
            </thead>
            <tbody></tbody>
        `;

        const tbody = table.querySelector('tbody');

        products.forEach(product => {
            const detail = details.find(d => d.product_code === product.productCode);
            if (detail) {
                const tr = document.createElement('tr');
                tr.dataset.productCode = product.productCode;
                tr.innerHTML = `
                    <td>${product.productCode}</td>
                    <td>${product.name}</td>
                    <td>${product.size}</td>
                    <td>${product.batch}</td>
                    <td>${product.processMethod}</td>
                    <td>
                        <div class="quantity-controls">
                            <button class="quantity-btn minus-btn" onclick="decreaseQuantity(this)">-</button>
                            <input type="number" class="quantity-input" value="0" min="0">
                            <button class="quantity-btn plus-btn" onclick="increaseQuantity(this)">+</button>
                        </div>
                    </td>
                `;
                tbody.appendChild(tr);
            }
        });

        resultArea.appendChild(table);
        document.getElementById('submissionForm').style.display = 'block';
    }

    // 增加数量
    function increaseQuantity(button) {
        const input = button.previousElementSibling;
        input.value = parseInt(input.value) + 1;
    }

    // 减少数量
    function decreaseQuantity(button) {
        const input = button.nextElementSibling;
        const value = parseInt(input.value);
        if (value > 0) {
            input.value = value - 1;
        }
    }

    // 提交生产数据
    function submitProductionData() {
        const planId = document.getElementById('resultArea').dataset.planId;
        const description = document.getElementById('description').value.trim();
        let userInfo = '未登录';
  try {
    const userData = localStorage.getItem('userInfo');
    if (userData) {
      const user = JSON.parse(userData);
      userInfo = user.name || '未登录';
    }
  } catch (e) { /* 忽略错误 */ }

        if (!planId) {
            alert('请先选择生产计划并搜索产品');
            return;
        }

        if (!description) {
            alert('请输入描述信息');
            return;
        }

        // 收集表格中的数据
        const rows = document.querySelectorAll('#resultArea table tbody tr');
        const details = Array.from(rows).map(row => {
            const productCode = row.dataset.productCode;
            const quantity = parseInt(row.querySelector('.quantity-input').value) || 0;
            return {
                product_code: productCode,
                product_quantity: quantity
            };
        }).filter(detail => detail.product_quantity > 0);

        if (details.length === 0) {
            alert('请至少设置一个产品的完成数量');
            return;
        }

        // 根据userInfo查询job_number
        fetch(`http://localhost:8080/api/persons/search?keyword=${userInfo}`)
           .then(response => {
                if (!response.ok) {
                    throw new Error('人员信息查询失败');
                }
                return response.json();
            })
           .then(persons => {
                if (!persons || persons.length === 0) {
                    alert('未找到对应的人员信息');
                    return;
                }
                const jobNumber = persons[0]?.jobNumber; // 可选链防止未定义错误
                    
                // 提交数据
                const submissionData = {
                    plan_id: planId,
                    description: description,
                    is_approved: false,
                    submitter_job_number: jobNumber
                };

                // 先提交主记录
                fetch('http://localhost:8080/api/production_submissions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(submissionData)
                })
               .then(response => {
                    if (!response.ok) {
                        throw new Error('提交失败: ' + response.statusText);
                    }
                    return response.json();
                })
               .then(submission => {
                    const submissionId = submission.submission_id;

                    // 提交详情记录
                    const detailPromises = details.map(detail => {
                        const detailData = {
                            submission_id: submissionId,
                            product_code: detail.product_code,
                            product_quantity: detail.product_quantity
                        };

                        return fetch('http://localhost:8080/api/production_submission_details', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(detailData)
                        });
                    });

                    return Promise.all(detailPromises);
                })
               .then(() => {
                    alert('提交成功！');
                    document.getElementById('description').value = '';
                    // 可选：清空表格中的数量
                    document.querySelectorAll('.quantity-input').forEach(input => {
                        input.value = '0';
                    });
                })
               .catch(error => {
                    console.error('提交过程中出错:', error);
                    alert('提交失败，请重试');
                });
            })
           .catch(error => {
                console.error('查询人员信息失败:', error);
                alert('查询人员信息失败，请重试');
            });
    }
</script>
</body>
</html>